//
//  NSDictionary+SafeValue.m
//  DK_TestApp
//
//  Created by DK on 2017/4/7.
//  Copyright © 2017年 ChunYu. All rights reserved.
//

#import "NSDictionary+SafeValue.h"
#import <objc/runtime.h>
#import "JRSwizzle.h"
@implementation NSDictionary (SafeValue)

+ (void)swizzleSEL:(SEL)originalSEL withSEL:(SEL)swizzledSEL {
    
    Class class = NSClassFromString(@"__NSPlaceholderDictionary");
    

    Method originalMethod = class_getInstanceMethod(class, originalSEL);
    Method swizzledMethod = class_getInstanceMethod(class, swizzledSEL);
    
    BOOL didAddMethod =
    class_addMethod(class,
                    originalSEL,
                    method_getImplementation(swizzledMethod),
                    method_getTypeEncoding(swizzledMethod));
    
    if (didAddMethod) {
        class_replaceMethod(class,
                            swizzledSEL,
                            method_getImplementation(originalMethod),
                            method_getTypeEncoding(originalMethod));
    } else {
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
}

+(void)load{
//    NSError *error;
//    [self jr_swizzleMethod:@selector(dictionaryWithObjects:forKeys:count:) withMethod:@selector(dkSwizzingClass_dictionaryWithObjects:forKeys:count:) error:&error];
    
//    [self swizzleSEL:@selector(dictionaryWithObjects:forKeys:count:) withSEL:@selector(dkSwizzingClass_dictionaryWithObjects:forKeys:count:)];
    
//    [self swizzleSEL:@selector(initWithObjects:forKeys:count:) withSEL:@selector(dkSwizzing_initWithObjects:forKeys:count:)];
}

- (instancetype)dkSwizzing_initWithObjects:(const id  _Nonnull __unsafe_unretained *)objects forKeys:(const id<NSCopying>  _Nonnull __unsafe_unretained *)keys count:(NSUInteger)cnt{
    id safeObjects[cnt];
    id safeKeys[cnt];
    
    NSUInteger j = 0;
    for (NSUInteger i = 0; i < cnt ; i++) {
        id key = keys[i];
        id obj = objects[i];
        if (!key || !obj) {
            continue;
        }
        safeObjects[j] = obj;
        safeKeys[j] = key;
        j++;
    }
    
//    NSLog(@"%@",self);
    return  [self dkSwizzing_initWithObjects:safeObjects forKeys:safeKeys count:j];
}




@end
